package core;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.toolbox.MultipartEntity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public abstract class MultipartRequest<T extends Data> extends DataRequest<T> {

    MultipartEntity mMultiPartEntity = new MultipartEntity();

    Map<String, String> mHeaders = new HashMap<>();

    public MultipartRequest(String url, DataListener listener) {
        super(Request.Method.POST, url, listener);
    }

    public MultipartRequest post(String key, File file) {
        mMultiPartEntity.addFilePart(key, file);
        return this;
    }

    public MultipartRequest postBitmap(String paramName, byte[] rawData) {
        mMultiPartEntity.addBitmapPart(paramName, rawData);
        return this;
    }

    /**
     * @return
     */
    public MultipartEntity getMultiPartEntity() {
        return mMultiPartEntity;
    }

    @Override
    public String getBodyContentType() {
        return mMultiPartEntity.getContentType().getValue();
    }

    public void addHeader(String key, String value) {
        mHeaders.put(key, value);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mHeaders;
    }

    @Override
    public byte[] getBody() {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            // multipart body
            mMultiPartEntity.writeTo(bos);
        } catch (IOException e) {
            Log.e("", "IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

}
